package com.zkingsoft.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.matrix.core.constance.MatrixConstance;
import com.matrix.core.tools.WebUtil;

/**
 * 身份认证拦截器
 * 
 * @author JIANGYOUYAO
 * @email 935090232@qq.com
 * @date 2017年12月8日
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

	/**
	 * 检查管理员是否登陆
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {

		String requestUrl = request.getRequestURI();
		// 如果访问特殊的路径需要验证管理员的登录权限
		if (requestUrl.indexOf("/admin/") != -1 || requestUrl.indexOf("/super/") != -1
				|| requestUrl.indexOf("/developer/") != -1 || requestUrl.indexOf("/customer/") != -1) {
			if (WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY) == null) {
				// 判断是否为异步请求
				String requestType = request.getHeader("X-Requested-With");
				if (requestType == null) {
					response.sendRedirect(request.getContextPath() + "/do/common/redirect/login");
				} else {
					response.getWriter().write("loginTimeOut...");
				}
				return false;
			} else {
				return true;
			}
		} else {
			return true;
		}
	}
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}
}
